package com.meihua.shellapp.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Response;
import com.meihua.shellapp.R;
import com.meihua.shellapp.activity.set.ChangePhoneActivity;
import com.meihua.shellapp.activity.set.SetPayPwdActiity;
import com.meihua.shellapp.base.BaseActivity;
import com.meihua.shellapp.base.BaseBean;
import com.meihua.shellapp.base.MyApplication;
import com.meihua.shellapp.common.NetHelper;
import com.meihua.shellapp.utils.FastClickUtils;
import com.meihua.shellapp.utils.MyStringCallBack;
import com.meihua.shellapp.utils.ToastUtils;
import com.meihua.shellapp.utils.URL;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

import butterknife.Bind;
import butterknife.OnClick;

/**
 * 验证手机号
 * 作者：lc on 2017/10/9.
 * 邮箱：lc0607live@163.com
 */

public class AuthenticationInfoActivity extends BaseActivity {

    @Bind(R.id.iv_top_left)
    ImageView iv_top_left;//返回
    @Bind(R.id.tv_title)
    TextView tv_title;//标题

    @Bind(R.id.tv_next)
    TextView tv_next;//下一步
    @Bind(R.id.tv_phone)
    EditText tv_phone;//手机号
    @Bind(R.id.tv_get_code)
    TextView tv_get_code;//获取验证码

    @Bind(R.id.et_verification_code)
    EditText mEtCode;//验证码

    private int type;//类型1。注册;2.登录;3找回密码;4.修改手机号;5.修改支付密码;

    private int time;//倒计时时间


    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what > 0) {
                tv_get_code.setBackgroundResource(R.drawable.btn_backgroud_gary_6);
                tv_get_code.setText(msg.what + "");
            } else {
                tv_get_code.setBackgroundResource(R.drawable.btn_backgroud_round_6);
                tv_get_code.setText("获取验证码");
            }
        }
    };

    @Override
    public int getLayoutId() {
        return R.layout.activity_authentication_info;
    }

    /**
     * 初始化View
     *
     * @param savedInstanceState
     */
    @Override
    public void initView(Bundle savedInstanceState) {
        type = getIntent().getIntExtra("type", 0);
        tv_title.setText("验证手机号");
        iv_top_left.setVisibility(View.VISIBLE);
        iv_top_left.setOnClickListener(this);
        tv_phone.setText(MyApplication.getInstance().bean == null ? "" : MyApplication.getInstance().bean.getPhone());
        if (MyApplication.getInstance().bean == null) {
            tv_phone.setFocusable(true);
            tv_phone.setFocusableInTouchMode(true);
            tv_phone.requestFocus();
        }
        tv_title.setVisibility(View.VISIBLE);
        tv_next.setOnClickListener(this);
        tv_get_code.setOnClickListener(this);
    }

    /**
     * 点击事件
     *
     * @param view
     */
    @Override
    public void onClick(View view) {
        super.onClick(view);
        Intent in = new Intent();
        switch (view.getId()) {
            case R.id.tv_get_code://获取验证码
                if (!tv_get_code.getText().toString().equals("获取验证码")) {
                    return;
                }
                if (tv_phone.getText().toString().equals("")) {
                    ToastUtils.getInstance().showToast("请输入手机号");
                    return;
                }
                if (tv_phone.getText().toString().length() != 11) {
                    ToastUtils.getInstance().showToast("手机号格式不对");
                    return;
                }
                sendCode(tv_phone.getText().toString());
                break;
            case R.id.tv_next://下一步
                if (FastClickUtils.isFastClick()) {
                    String trim = mEtCode.getText().toString().trim();
                    if (!TextUtils.isEmpty(trim)) {
                        submit(trim);
                    }
                }
                break;
        }
    }

    /*验证验证码 下一步*/
    private void submit(final String trim) {
        Map<String, String> params = new HashMap() {{
            put("phone", tv_phone.getText().toString());
            put("type", type + "");
            put("mid", MyApplication.getInstance().getMId());
            put("code", trim);
        }};
        NetHelper.post(URL.getUrl().CHECKPHONE, params, new NetHelper.HttpCallBack() {
            @Override
            public void onSuccess(Response<String> response) {
                try {
                    JSONObject object = new JSONObject(response.body());
                    setData();
                    if (object.getInt("code") == 1) {
                    } else {
                        Toast.makeText(AuthenticationInfoActivity.this, "验证码错误", Toast.LENGTH_SHORT).show();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }, false);
    }

    /**
     * 设置数据
     */
    private void setData() {
        Intent intent;
        switch (type) {
            case 1:
                break;
            case 3://找回密码
                intent = new Intent(AuthenticationInfoActivity.this, SetNewPwdActivity.class);
                intent.putExtra("phone", tv_phone.getText().toString());
                startActivity(intent);
                finish();
                break;
            case 6:
                //更改手机号
                intent = new Intent(AuthenticationInfoActivity.this, ChangePhoneActivity.class);
                intent.putExtra("phone", tv_phone.getText().toString());
                startActivity(intent);
                finish();
                break;
            case 5:
                //支付密码
                intent = new Intent(AuthenticationInfoActivity.this, SetPayPwdActiity.class);
                intent.putExtra("phone", tv_phone.getText().toString());
                startActivity(intent);
                finish();
                break;
        }
    }

    /**
     * 发送验证码
     */
    private void sendCode(String phone) {
        OkGo.<String>post(URL.getUrl().SENDCODE)
                .params("phone", phone)
                .params("type", type)
                .execute(new MyStringCallBack<BaseBean>(tv_next) {
                    @Override
                    public void onSuccessData(BaseBean baseBean) {
                        super.onSuccessData(baseBean);
                        if (baseBean.getCode() == 1) {
                            countDown(60);//倒计时
                        }
                        ToastUtils.getInstance().showToast(baseBean.getMsg());
                    }
                });
    }


    /**
     * 倒计时
     *
     * @param timetemp 时间(s)
     */
    private void countDown(int timetemp) {
        time = timetemp;
        new Thread(new Runnable() {
            @Override
            public void run() {
                if (time < 0) {
                    return;
                }
                time--;
                try {
                    Thread.sleep(1000);
                    handler.sendEmptyMessage(time);
                    run();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                    return;
                }

            }
        }).start();
    }

    @OnClick(R.id.iv_top_left)
    public void onViewClicked() {
        finish();
    }
}
